package com.tanhua.server.service;

import com.alibaba.fastjson.JSON;
import com.tanhua.commons.templates.HuanXinTemplate;
import com.tanhua.domain.db.Question;
import com.tanhua.domain.db.UserInfo;
import com.tanhua.domain.mongo.RecommendUser;
import com.tanhua.domain.vo.PageResult;
import com.tanhua.domain.vo.RecommendUserQueryParam;
import com.tanhua.domain.vo.TodayBestVo;
import com.tanhua.dubbo.api.QuestionApi;
import com.tanhua.dubbo.api.mongo.RecommendUserApi;
import com.tanhua.dubbo.api.UserInfoApi;
import com.tanhua.server.interceptor.UserHolder;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.RandomUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 今日佳人业务处理层
 */
@Service
@Slf4j
public class TodayBestService {
    @Reference
    private RecommendUserApi recommendUserApi;

    @Reference
    private UserInfoApi userInfoApi;

    @Reference
    private QuestionApi questionApi;

    @Autowired
    private HuanXinTemplate huanXinTemplate;

    /**
     * 今日佳人
     */
    public TodayBestVo todayBest() {
        //定义返回VO
        TodayBestVo todayBestVo = new TodayBestVo();
        Long toUserId = UserHolder.getUserId();
        //a.根据登录用户id 查询 recommend_user 推荐用户表 得到缘分值、推荐用户id(一条)
        RecommendUser recommendUser = recommendUserApi.todayBest(toUserId);
        //b.如果没有查询到推荐用户，则设置默认用户
        if(recommendUser == null){
            recommendUser = new RecommendUser();
            recommendUser.setUserId(1l);//默认淡水维哥_00001
            recommendUser.setScore(100d);//缘分值100分
        }
        //获取推荐用户id
        commonRecommendUser(recommendUser, todayBestVo);
        return todayBestVo;
    }

    /**
     * 首页推荐用户
     */
    public PageResult<TodayBestVo> recommendation(RecommendUserQueryParam param) {
        Long toUserId = UserHolder.getUserId();//当前登录用户id
        PageResult<TodayBestVo> voPageResult = new PageResult<>();
        //a.根据当前登录用户id page pagesize 作为条件分页查询PageResult<RecommendUser>
        PageResult<RecommendUser> pageResult = recommendUserApi.findPage(toUserId,param.getPage(),param.getPagesize());
        List<RecommendUser> records = (List<RecommendUser>) pageResult.getItems();
        if(pageResult == null || records == null){
            //设置默认数据
            pageResult = new PageResult(10l,param.getPagesize().longValue(),1l,param.getPage().longValue(),null);
            records = defaultRecommend();
        }
        //将List<RecommendUser> 转为List<TodayBestVo>
        //将List<TodayBestVo> set到PageResult<TodayBestVo>中
        List<TodayBestVo> bestVoList = new ArrayList<>();
        //b.循环遍历，根据推荐用户id查询user_info得到用户信息
        for (RecommendUser recommendUser : records) {
            TodayBestVo todayBestVo = new TodayBestVo();

            commonRecommendUser(recommendUser, todayBestVo);

            bestVoList.add(todayBestVo);
        }

        //c.封装VO
        BeanUtils.copyProperties(pageResult,voPageResult);
        voPageResult.setItems(bestVoList);
        return voPageResult;
    }

    /**
     * 根据MongDB查询推荐用户 再查询UserInfo公共方法
     * @param recommendUser
     * @param todayBestVo
     */
    private void commonRecommendUser(RecommendUser recommendUser, TodayBestVo todayBestVo) {
        //获取推荐用户id
        Long userId = recommendUser.getUserId();
        //c.根据推荐用户id  到 user_info用户信息表查询 得到头像、性别等信息
        UserInfo userInfo = userInfoApi.findByUserId(userId);
        BeanUtils.copyProperties(userInfo, todayBestVo);
        if (userInfo.getTags() != null) {
            todayBestVo.setTags(userInfo.getTags().split(","));//标签设置
        }
        //d.封装TodayBestVo返回app
        todayBestVo.setFateValue(new Double(recommendUser.getScore()).longValue());//缘分值
    }


    //构造默认数据
    private List<RecommendUser> defaultRecommend() {
        String ids = "1,2,3,4,5,6,7,8,9,10";
        List<RecommendUser> records = new ArrayList<>();
        for (String id : ids.split(",")) {
            RecommendUser recommendUser = new RecommendUser();
            recommendUser.setUserId(Long.valueOf(id));
            recommendUser.setScore(RandomUtils.nextDouble(70, 98));
            records.add(recommendUser);
        }
        return records;
    }

    /**
     * 查看用户详情
     */
    public TodayBestVo queryUserDetail(Long beautyUserId) {
        TodayBestVo vo = new TodayBestVo();
        //1.根据佳人用户id查询佳人详情信息
        UserInfo userInfo = userInfoApi.findByUserId(beautyUserId);
        BeanUtils.copyProperties(userInfo,vo);
        if(StringUtils.isNotEmpty(userInfo.getTags())){
            vo.setTags(userInfo.getTags().split(","));
        }
        //2.根据佳人用户id 和 当前登录用户id 从推荐表 中 查询缘分值
        Long score = recommendUserApi.queryForScore(beautyUserId,UserHolder.getUserId());
        vo.setFateValue(score);
        log.debug(vo.toString());
        return  vo;
    }

    /**
     * 查询陌生人问题
     */
    public String strangerQuestions(Long userId) {
        //1.根据佳人用户id查询设置陌生人问题
        Question question = questionApi.findByUserId(userId);
        //2.如果为空 设置默认问题
        if(question == null || StringUtils.isEmpty(question.getTxt())){
            return "为什么要加我？是要约我吗？";
        }
        return question.getTxt();
    }
    /**
     * 回复陌生人问题
     * beautyUserId:佳人用户id(陌生人用户id)
     */
    public void answerQuestions(long beautyUserId, String reply) {
        Long userId = UserHolder.getUserId();
        //a.根据当前登录用户id查询userInfo 得到userInfo nickname（服务已经实现）
        UserInfo userInfo = userInfoApi.findByUserId(userId);
        //b.根据佳人用户id 查询问题表 得到问题 （服务已经实现）
        Question question = questionApi.findByUserId(beautyUserId);
        String txt = "为什么要加我？是要约我吗？";;
        if(question != null && StringUtils.isNotEmpty(question.getTxt())){
            txt = question.getTxt();
        }
        //c.调用环信云工具方法sendMsg将消息传入（工具类）
        Map<String,String> map = new HashMap<>();
        map.put("userId",userId.toString());//当前登录用户id
        map.put("nickname",userInfo.getNickname());//当前登录用户昵称
        map.put("strangerQuestion",txt);//佳人问题
        map.put("reply",reply);//回复内容
        String msg = JSON.toJSONString(map);//将map对象转为string字符传入huanXinTemplate
        log.debug("***************msg************************"+msg);
        huanXinTemplate.sendMsg(String.valueOf(beautyUserId),msg);
    }
}
